package com.biglead.wx.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.biglead.common.pojo.MiniLoginCodeRequest;
import com.biglead.common.pojo.MiniLoginRequest;
import com.biglead.wx.pojo.WxAppInfo;
import com.biglead.wx.service.WxAppInfoService;
import com.biglead.wx.service.WxAppLoginService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxAppLoginServiceImpl implements WxAppLoginService {

    //查询数据库小程序配置
    @Autowired
    private WxAppInfoService wxAppInfoService;

    @Override
    public Map<String, Object> login(MiniLoginRequest request) throws WxErrorException {


        final WxMaService wxService = getWxMaService(request.getAppId());

        // 获取微信用户session
        WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(request.getCode());
        if (null == session) {
            throw new RuntimeException("login handler error");
        }
        String openid = session.getOpenid();
        String sessionKey = session.getSessionKey();
        String unionid = session.getUnionid();
        log.info("微信登录 openid {} unionid {} sessionKey {}", openid, unionid, sessionKey);


        String iv = request.getIv();
        String encryptedData = request.getEncryptedData();
        String rawData = request.getRawData();
        String signature = request.getSignature();

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {

        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

        String nickName = userInfo.getNickName();
        String avatarUrl = userInfo.getAvatarUrl();
        String unionId = userInfo.getUnionId();

        Map<String, Object> map = new HashMap<>();
        map.put("openId", openid);
        map.put("unionId", unionId);
        map.put("sessionKey", sessionKey);
        map.put("code", 200);

        map.put("nickName", nickName);
        map.put("avatarUrl", avatarUrl);

        return map;

    }

    @Override
    public WxMaUserInfo info(MiniLoginRequest loginDTO) {
        final WxMaService wxService = getWxMaService(loginDTO.getAppId());

        String iv = loginDTO.getIv();
        String encryptedData = loginDTO.getEncryptedData();
        String rawData = loginDTO.getRawData();
        String signature = loginDTO.getSignature();
        String sessionKey = loginDTO.getSessionKey();

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {

        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

        return userInfo;
    }

    @Override
    public Map<String, Object> phone(MiniLoginRequest loginDTO) {

        final WxMaService wxService = getWxMaService(loginDTO.getAppId());

        String iv = loginDTO.getIv();
        String encryptedData = loginDTO.getEncryptedData();
        String sessionKey = loginDTO.getSessionKey();

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phoneNoInfo.getPhoneNumber());
        map.put("sessionKey", sessionKey);
        map.put("code", 200);
        return map;
    }

    @Override
    public Map<String, Object> loginByCode(MiniLoginCodeRequest loginDTO) {

        //根据AppId,获取基本配置，构建 WxMaService
        final WxMaService wxService = getWxMaService(loginDTO.getAppId());

        // 获取微信用户session
        WxMaJscode2SessionResult session = null;
        try {
            session = wxService.getUserService().getSessionInfo(loginDTO.getCode());
        } catch (WxErrorException e) {
            Map<String, Object> map = new HashMap<>();
            map.put("message", e.getMessage());
            map.put("code", 400);
            return map;
        }
        if (null == session) {
            Map<String, Object> map = new HashMap<>();
            map.put("message", "获取session失败");
            map.put("code", 400);
            return map;

        }
        String openid = session.getOpenid();
        String sessionKey = session.getSessionKey();
        log.info("微信登录 openid {}  sessionKey {}", openid, sessionKey);

        Map<String, Object> map = new HashMap<>();
        map.put("openId", openid);
        map.put("sessionKey", sessionKey);
        map.put("code", 200);
        return map;
    }

    private WxMaService getWxMaService(String appId) {
        //查询数据库小程序的配置
        WxAppInfo wxAppInfo = wxAppInfoService.queryByAppId(appId);
        String appSecret = wxAppInfo.getSecret();

        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(appId);
        config.setSecret(appSecret);
        config.setMsgDataFormat("JSON");
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(config);
        return wxMaService;
    }
}
